<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import OSS from 'ali-oss'

// 创建OSS客户端
const client = new OSS({
  region: 'oss-cn-chengdu',
  accessKeyId: 'LTAI5tKsESaCVvxSMvZb4vCb',
  accessKeySecret: 'wLzCbAtNyQlJ6PZX5J2LAFCZrYFce7',
  bucket: 'one-byte'
})

const uploadProgress = ref(0)
const isUploading = ref(false)

// 生成随机文件名
const generateFileName = (file) => {
  const originalName = file.name.split('.')[0] // 获取原始文件名（不含扩展名）
  const timestamp = Date.now()
  const random = Math.random().toString(36).substring(2, 8)
  const ext = file.name.split('.').pop()
  return `video/${originalName}-${timestamp}-${random}.${ext}`
}

// 处理上传
const handleUpload = async (file) => {
  if (!file) return

  // 检查文件类型
  const isVideo = file.type.startsWith('video/')
  if (!isVideo) {
    ElMessage.error('请上传视频文件')
    return false
  }

  isUploading.value = true
  const fileName = generateFileName(file)

  try {
    // 上传文件到OSS
    const result = await client.multipartUpload(fileName, file, {
      progress: (p) => {
        uploadProgress.value = Math.floor(p * 100)
      }
    })

    if (result.res.status === 200) {
      ElMessage.success('上传成功')
      uploadProgress.value = 100
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请重试')
  } finally {
    isUploading.value = false
    uploadProgress.value = 0
  }
}

// 上传之前的钩子
const beforeUpload = (file) => {
  if (isUploading.value) {
    ElMessage.warning('正在上传中，请等待...')
    return false
  }
  return true
}
</script>

<template>
  <div class="upload-container">
    <el-upload
      class="upload-component"
      drag
      action=""
      :auto-upload="false"
      :show-file-list="false"
      :before-upload="beforeUpload"
      @change="(file) => handleUpload(file.raw)"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        拖拽文件到此处或 <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          请上传视频文件
        </div>
      </template>
    </el-upload>

    <!-- 进度条 -->
    <el-progress
      v-if="isUploading"
      :percentage="uploadProgress"
      :stroke-width="20"
      status="success"
    />
  </div>
</template>

<style>
@import 'element-plus/dist/index.css';

.upload-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.upload-component {
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
}

.el-upload__text {
  margin: 10px 0;
  color: #606266;
}

.el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.el-icon--upload {
  font-size: 48px;
  color: #909399;
  margin-bottom: 10px;
}
</style>
